package com.training.web.service;

import com.training.bean.Feedback;
import com.training.bean.User;
import com.training.web.repository.WebFeedbackRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class WebFeedbackService {

    @Autowired
    private WebFeedbackRepository webFeedbackRepository;
    
    @Autowired
    private WebUserService webUserService;

    /**
     * 保存意见反馈
     * @param uid 用户ID
     * @param content 反馈内容
     * @return 保存后的Feedback对象
     */
    public Feedback saveFeedback(int uid, String content) {
        Feedback feedback = new Feedback();
        feedback.setUid(uid);
        feedback.setContent(content);
        feedback.setCreate_date(new Date());
        return webFeedbackRepository.save(feedback);
    }

    /**
     * 获取所有意见反馈
     * @return Feedback列表
     */
    public List<Feedback> getAllFeedback() {
        List<Feedback> feedbackList = webFeedbackRepository.findAll();
        
        // 为每个反馈添加用户信息
        for (Feedback feedback : feedbackList) {
            try {
                User user = webUserService.findUserById(feedback.getUid());
                if (user != null) {
                    feedback.setUserNickname(user.getNickname());
                    feedback.setUserPhone(user.getPhone());
                }
            } catch (Exception e) {
                // 如果获取用户信息失败，保持字段为null
                System.err.println("获取用户信息失败，用户ID: " + feedback.getUid() + "，错误: " + e.getMessage());
            }
        }
        
        return feedbackList;
    }

    /**
     * 根据ID删除意见反馈
     * @param id 意见反馈ID
     */
    public void deleteFeedback(int id) {
        webFeedbackRepository.deleteById(id);
    }
}